﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using ProceduralGolf.generation;
using JigLibX.Utils;
using JigLibX.Physics;
using JigLibX.Collision;
using ProceduralGolf.terrain;

namespace ProceduralGolf.physics
{
    class TerrainObject : PhysicsObject
    {
        public CollisionSkin Skin { get { return skin; } }


        public TerrainObject(Game game, BinaryTriangleTerrain terrain)
            : base(Vector3.Zero, Vector3.One)
        {
            LoadingScreen.GetLoadingScreen(game).Message = "enter TerrainObject constructor";
            Heightmap heightmap = terrain.Heightmap;
            float scale = terrain.Scale;

            int width = heightmap.Width;
            int height = heightmap.Height;

            float offset_x = (width*scale) / 2.0f;
            float offset_z = (height*scale) / 2.0f;
            LoadingScreen.GetLoadingScreen(game).Message = "start creating array2d";
            Array2D array = new Array2D(width, height, 0.0f);
            LoadingScreen.GetLoadingScreen(game).Message = "end creating array2d";
            LoadingScreen.GetLoadingScreen(game).Message = "start setting array2d content";
            for (int x = 0; x < width; ++x)
            {
                for (int y = 0; y < height; ++y)
                {
                    array.SetAt(x, y, heightmap.getHeight(x, y)*scale);
                }
            }
            LoadingScreen.GetLoadingScreen(game).Message = "end setting array2d content";
            LoadingScreen.GetLoadingScreen(game).Message = "start physics stuff";
            body = new Body();
            skin = new CollisionSkin(null);
            body.MoveTo(new Vector3(offset_x, 0, offset_z), Matrix.Identity);
            LoadingScreen.GetLoadingScreen(game).Message = "create jiglibx heightmap";
            JigLibX.Geometry.Heightmap hmap = new JigLibX.Geometry.Heightmap(array, offset_x, offset_z, scale, scale);
            LoadingScreen.GetLoadingScreen(game).Message = "end create jiglibx heightmap";
            LoadingScreen.GetLoadingScreen(game).Message = "add primitive to skin";
            skin.AddPrimitive(hmap, new MaterialProperties(0.5f, 1.0f, 1.0f));
            LoadingScreen.GetLoadingScreen(game).Message = "add skin to collisionsystem";
            PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(skin);
            LoadingScreen.GetLoadingScreen(game).Message = "end physics stuff";
        }


    }
}
